import random
import re

import redis
from flask import make_response
import json
from flask import Blueprint, request, jsonify

from Laboratory.db import db
from Laboratory.models.user import UsersModel
from Laboratory.util.captcha.captcha import captcha
from Laboratory.util.comm import send_message
from Laboratory.util.myjwt import myjwt
from Laboratory.util.myredis import r
import time

from Laboratory.util.sms_code import sms_send

user_blue = Blueprint("user", __name__)

@user_blue.route("/test")
def test():
    time.sleep(3)
    return jsonify({"code": 200, "mes": "mes"})

@user_blue.route('/getcode')
def get_img():
    name, text, img = captcha.generate_captcha()
    uuid = request.args.get('uuid')
    r.str_setex(uuid, text, 300)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>", cls.get(uuid))
    res = make_response(img)
    res.headers['Content-Type'] = "image/jpg"
    return res

# 发送短信接口
@user_blue.route("/sendSmsCode", methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data["uuid"]
        mobile = data["mobile"]
        image_code = data["image_code"]
        if not all ([uuid, mobile, image_code]):
            return jsonify({"code": 400, 'msg': "'图片验证码或手机号未输入'"})
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return jsonify({"code": 400, 'msg': "手机号格式错误"})
        uuid_code = r.str_get(uuid)
        if uuid_code:
            ucode = uuid_code.decode()
            print(ucode)
        else:
            return jsonify({'code': 400, 'msg': '图片验证码已过期'})
        if ucode.lower() != image_code.lower():
            return jsonify({'code': 400, 'msg': '图片验证码错误'})

        r.list_push("sms_", mobile)
        mobi = r.str_get(mobile)
        if mobi:
            return jsonify({'code': 400, 'msg': '一分钟内不能重复发送'})
        else:
            while True:
                for i in range(2):
                    len = r.list_len('sms_')
                    if len > 0 or len < 2:
                        value = r.list_pop('sms_')
                        print(value)
                        mobile = value.decode()
                        code = random.randint(100000, 999999)
                        r.str_setex(mobile, code, 60)
                        res = sms_send(mobile, code)
                        if res:
                            return jsonify({"code": 200, "msg": "发送成功"})
                        return jsonify({"code": 400, 'msg': '发送失败'})


@user_blue.route("/login", methods=["POST"])
def sendSmsCode():
    data = json.loads(request.data)
    # mobile = data['mobile']
    mobile = '13253059888'
    sms_code = data['sms_code']
    new = r.str_get(mobile)
    print(333333333333333333333333, new)
    if sms_code != new.decode():
        return jsonify({"code": 400, "msg": "验证码错误"})
    r.del_key(mobile)
    sql = "select * from user where mobile='%s'" % mobile
    use = db.findOne(sql)
    if not use:
        sql = "insert into user(mobile, nikename) values('%s', '%s')" % (mobile, mobile[-4:])
        db.add(sql)
        db.commit()
    sql = "select * from user where mobile='%s'" % mobile
    use = db.findOne(sql)
    data = {'data': {'user_id': use['id'], 'mobile': use['mobile'], 'exp': int(time.time())}}
    token = myjwt.jwt_encode(data)
    return jsonify({"code": 200, "token": token, "user_id": use['id']})







